<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Exception;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class HomeController extends Controller
{
    /**
     * index 
     * 
     * @return json
     */
    public function index(Request $request)
    {
        return success(["a" => 1]);
    }

    /**
     * method1, return request 
     * 
     * @return json
     */
    public function method1(Request $request)
    {
        return $request;
    }

    /**
     * method2, throw exception
     * 
     * @return json
     */
    public function method2(Request $request)
    {
        throw new NotFoundHttpException("content not found");
    }


    /**
     * method3, code error
     * 
     * @return json
     */
    public function method3()
    {
        return success111([]);
    }

    /**
     * method4, test s logic
     * 
     * @return json
     */
    public function method4(Request $request)
    {
        $s = $request->get('s', '');

        if (strlen($s) < 1) {
            throw new Exception("param s can't be empty");
        }

        if (strlen($s) > 1000) {
            throw new Exception("param s too long");
        }

        $result = $this->isValid($s);
        return success(['result' => $result]);
    }


    /**
     * judgement str is valid
     * 
     * @param string $str
     * @return bool
     */
    private function isValid($str)
    {
        $stack = [];
        $brackets = [
            '{' => '}',
            '[' => ']',
            '(' => ')'
        ];

        for ($i = 0; $i < strlen($str); $i++) {
            $char = $str[$i];
            if (in_array($char, ['{', '[', '('])) {
                array_push($stack, $char);
            } else {
                if (empty($stack)) {
                    return false;
                }
                $top = array_pop($stack);
                if ($brackets[$top] != $char) {
                    return false;
                }
            }
        }

        return empty($stack);
    }
}
